import { defineComponent, ref, PropType } from 'vue'

export default defineComponent({
  name: 'EnvConfigModal',
  props: {
    env: {
      type: Object as PropType<Record<string, string>>,
      required: true,
    },
    onClose: {
      type: Function as PropType<() => void>,
      required: true,
    },
    onSave: {
      type: Function as PropType<(env: Record<string, string>) => void>,
      required: true,
    },
  },
  setup(props) {
    const envVars = ref<{ key: string; value: string }[]>(
      Object.entries(props.env).map(([key, value]) => ({ key, value }))
    )

    const addEnvVar = () => {
      envVars.value.push({ key: '', value: '' })
    }

    const removeEnvVar = (index: number) => {
      envVars.value.splice(index, 1)
    }

    const handleSave = () => {
      const env = envVars.value.reduce(
        (acc, { key, value }) => {
          if (key) acc[key] = value
          return acc
        },
        {} as Record<string, string>
      )
      props.onSave(env)
    }

    return () => (
      <div class="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
        <div class="bg-[#2D1A45] rounded-lg p-6 w-[600px] border border-[#3D2A55]">
          <h2 class="text-xl font-bold mb-4 text-white">环境变量配置</h2>

          <div class="space-y-3 max-h-[400px] overflow-y-auto">
            {envVars.value.map((envVar, index) => (
              <div key={index} class="flex gap-2">
                <input
                  v-model={envVar.key}
                  class="flex-1 bg-[#1A1A1A] border border-[#3D2A55] rounded px-3 py-2 text-white"
                  placeholder="变量名"
                />
                <input
                  v-model={envVar.value}
                  class="flex-1 bg-[#1A1A1A] border border-[#3D2A55] rounded px-3 py-2 text-white"
                  placeholder="变量值"
                />
                <button
                  onClick={() => removeEnvVar(index)}
                  class="px-3 py-2 bg-red-600 text-white rounded hover:bg-red-700"
                >
                  删除
                </button>
              </div>
            ))}
          </div>

          <div class="flex justify-between mt-4">
            <button
              onClick={addEnvVar}
              class="px-4 py-2 bg-[#4D3A65] text-white rounded hover:bg-[#5D4A75]"
            >
              添加变量
            </button>
            <div class="space-x-2">
              <button
                onClick={props.onClose}
                class="px-4 py-2 bg-[#3D2A55] text-white rounded hover:bg-[#4D3A65]"
              >
                取消
              </button>
              <button
                onClick={handleSave}
                class="px-4 py-2 bg-[#6D5A85] text-white rounded hover:bg-[#7D6A95]"
              >
                保存
              </button>
            </div>
          </div>
        </div>
      </div>
    )
  },
})
